package com.mall.ums.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.model.domain.ums.*;
import com.mall.ums.service.*;
import com.mall.utils.PageResult;
import com.mall.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuRelationService roleMenuRelationService;

    @Autowired
    private RoleResourceRelationService roleResourceRelationService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private ResourceService resourceService;

    /**
     * 给角色分配菜单
     *
     * @param
     * @param
     * @return
     */
    @PostMapping("/allocMenu")
    public R allocMenu(Long roleId, @RequestParam("menuIds") Long[] mis) {


        //如果角色有菜单，就删除，再插入
        LambdaQueryWrapper<RoleMenuRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenuRelation::getRoleId, roleId);
        List<RoleMenuRelation> menuRelations = roleMenuRelationService.list(queryWrapper);
        List<Long> menuIds = (List<Long>) Convert.toList(mis);
        if (CollUtil.isEmpty(menuRelations)) {
            //如何角色没有菜单，就插入
            List<RoleMenuRelation> roleMenuRelations = menuIds.stream().map(item -> {
                RoleMenuRelation roleMenuRelation = new RoleMenuRelation();
                roleMenuRelation.setMenuId(item);
                roleMenuRelation.setRoleId(roleId);
                return roleMenuRelation;
            }).collect(Collectors.toList());
            roleMenuRelationService.saveBatch(roleMenuRelations);
        } else {
            roleMenuRelationService.remove(queryWrapper);
            if (mis.length == 0) {
                return R.success("修改成功");
            }
            List<RoleMenuRelation> roleMenuRelations = menuIds.stream().map(item -> {
                RoleMenuRelation roleMenuRelation = new RoleMenuRelation();
                roleMenuRelation.setMenuId(item);
                roleMenuRelation.setRoleId(roleId);
                return roleMenuRelation;
            }).collect(Collectors.toList());
            roleMenuRelationService.saveBatch(roleMenuRelations);
        }

        return R.success("添加权限成功");
    }

    /**
     * 给角色分配资源
     *
     * @param roleId
     * @param ris
     * @return
     */
    @PostMapping("/allocResource")
    public R allocResource(Long roleId, @RequestParam("resourceIds") Long[] ris) {

        //1.如果有资源就删除，再插入
        LambdaQueryWrapper<RoleResourceRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleResourceRelation::getRoleId, roleId);
        List<RoleResourceRelation> list = roleResourceRelationService.list(queryWrapper);
        List<Long> resourceIds = (List<Long>) Convert.toList(ris);
        if (!CollUtil.isEmpty(list)) {
            roleResourceRelationService.remove(queryWrapper);
        }
        if (ris.length == 0) {
            return R.success("修改成功");
        }
        //2.如果没有资源就直接插入
        List<RoleResourceRelation> resourceRelations = resourceIds.stream().map(item -> {
            RoleResourceRelation roleResourceRelation = new RoleResourceRelation();
            roleResourceRelation.setRoleId(roleId);
            roleResourceRelation.setResourceId(item);
            return roleResourceRelation;
        }).collect(Collectors.toList());

        boolean saveBatch = roleResourceRelationService.saveBatch(resourceRelations);
        if (saveBatch) {
            return R.success("更改资源成功");
        } else {
            return R.error("更改资源失败");
        }
    }

    /**
     * 角色插入
     *
     * @param role
     * @return
     */
    @PostMapping("/create")
    public R create(@RequestBody Role role) {
        boolean save = roleService.save(role);
        if (save) {
            return R.success("插入成功");
        } else {
            return R.error("插入失败");
        }
    }

    /**
     * 批量删除角色
     * 这里有点问题
     *
     * @param map
     * @return
     */
    @PostMapping("/delete")
    public R delete(@RequestParam("ids") Long[] ids1) {
        List<Long> ids = (List<Long>) Convert.toList(ids1);
        //1.删除角色表
        roleService.removeByIds(ids);

        //2.删除分配资源表
        LambdaQueryWrapper<RoleResourceRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RoleResourceRelation::getRoleId, ids);
        roleResourceRelationService.remove(queryWrapper);

        //3.删除分配菜单表
        LambdaQueryWrapper<RoleMenuRelation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(RoleMenuRelation::getRoleId, ids);
        boolean remove = roleMenuRelationService.remove(lambdaQueryWrapper);

        //4.删除权限表

        if (remove) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    /**
     * 根据角色名称分页获取角色列表
     *
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public R<PageResult> list(String keyword, @RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Role> rolePage = new Page<>();
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(keyword != null, Role::getName, keyword);
        roleService.page(rolePage, queryWrapper);
        PageResult pageResult = PageResult.init(rolePage);
        return R.success(pageResult);
    }

    /**
     * 获取所有角色
     *
     * @return
     */
    @GetMapping("/listAll")
    public R<List> listAll() {
        List<Role> roleList = roleService.list(null);
        if (!CollUtil.isEmpty(roleList)) {
            return R.success(roleList);
        } else {
            return R.error("暂无数据");
        }
    }

    /**
     * 获取角色相关菜单
     *
     * @param roleId
     * @return
     */
    @GetMapping("/listMenu/{roleId}")
    public R<List> listMenu(@PathVariable Integer roleId) {
        LambdaQueryWrapper<RoleMenuRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenuRelation::getRoleId, Long.valueOf(roleId));
        List<RoleMenuRelation> roleMenuRelations = roleMenuRelationService.list(queryWrapper);
        List<Long> menus = roleMenuRelations.stream().map(item -> {
            return item.getMenuId();
        }).collect(Collectors.toList());

        List<Menu> menuList = new ArrayList<>();
        if (!CollUtil.isEmpty(menus)) {
            menuList = menuService.listByIds(menus);
        }

        if (!CollUtil.isEmpty(menuList)) {
            return R.success(menuList);
        } else {
            return R.error("无菜单明细");
        }
    }

    /**
     * 获取角色相关资源
     *
     * @param roleId
     * @return
     */
    @GetMapping("/listResource/{roleId}")
    public R<List> listResource(@PathVariable Integer roleId) {
        LambdaQueryWrapper<RoleResourceRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleResourceRelation::getRoleId, Long.valueOf(roleId));
        List<RoleResourceRelation> roleResourceRelation = roleResourceRelationService.list(queryWrapper);
        List<Long> resourceIds = roleResourceRelation.stream().map(item -> {
            return item.getResourceId();
        }).collect(Collectors.toList());
        List<Resource> resourceList = new ArrayList<>();
        if (!CollUtil.isEmpty(resourceIds)) {
            resourceList = resourceService.listByIds(resourceIds);
        }
        if (!CollUtil.isEmpty(resourceList)) {
            return R.success(resourceList);
        } else {
            return R.error("无资源明细");
        }
    }

    /**
     * 修改角色
     *
     * @param id
     * @param role
     * @return
     */
    @PostMapping("/update/{id}")
    public R updateById(@PathVariable Integer id, @RequestBody Role role) {
        role.setId(Long.valueOf(id));
        boolean update = roleService.updateById(role);
        if (update) {
            return R.success("更新成功");
        } else {
            return R.error("更新失败");
        }
    }

    /**
     * 修改角色状态
     *
     * @param map
     * @param id
     * @return
     */
    @PostMapping("/updateStatus/{id}")
    public R updateStatus(Integer status, @PathVariable String id) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getId, Long.valueOf(id));
        Role role = roleService.getById(Long.valueOf(id));
        role.setStatus(status);
        boolean update = roleService.update(role, queryWrapper);
        if (update) {
            return R.success("更新状态成功");
        } else {
            return R.error("更新状态失败");
        }
    }
}
